package top.ochiamalu.aioj.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * ws握手拦截器
 *
 * @author ochiamalu
 * @date 2025/01/24
 */
@Slf4j
@Component
public class WsHandshakeInterceptor implements HandshakeInterceptor {
    @Override
    public boolean beforeHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response,
                                   @NotNull WebSocketHandler wsHandler, @NotNull Map<String, Object> attributes) {
        log.info("WebSocket连接握手开始...");
        try {
            if (request instanceof ServletServerHttpRequest) {
                // 验证用户是否登录
                if (!StpUtil.isLogin()) {
                    log.error("用户未登录，WebSocket连接被拒绝");
                    return false;
                }

                long userId = StpUtil.getLoginIdAsLong();
                log.info("当前连接用户ID: {}", userId);
                attributes.put("userId", userId);
                return true;
            }
        } catch (Exception e) {
            log.error("WebSocket握手过程发生错误", e);
        }
        return false;
    }

    @Override
    public void afterHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response,
                               @NotNull WebSocketHandler wsHandler, Exception exception) {
        if (exception != null) {
            log.error("WebSocket握手后发生错误", exception);
        } else {
            log.info("WebSocket连接握手完成");
        }
    }
}
